<?php

namespace app\proxy\model\employ;

use app\common\model\employ\Poster as PosterModel;
use app\proxy\model\proxy\Region;

class Poster extends PosterModel
{


    public function getList($params, $regionIds, $proxyId)
    {
        $model = $this;
        if (isset($params['search']) && $params['search']) {
            $model = $model->where('name', 'like', '%' . $params['search'] . '%');
        }
        if (isset($params['is_audit'])) {
            $model = $model->where('is_audit', $params['is_audit']);
        }
        // 查询列表数据
        return $model->with(["qr_code",'bg_image'])->where('is_delete', '=', '0')
            ->where(function ($query) use ($params, $regionIds, $proxyId) {
                if (empty($params["proxy_id"])) {
                    $query->whereOr("province_id", "in", $regionIds)->whereOr("city_id", "in", $regionIds)->whereOr("proxy_id", $proxyId);
                } else {
                    $query->where("proxy_id", $params["proxy_id"]);
                }
            })
            ->withAttr('proxy_name', function ($value, $data) use ($proxyId) {
                return Region::getProxyName($data, $proxyId);
            })->withAttr('city_name', function ($value, $data) {
                return \app\common\model\region\Region::getMergerName($data["city_id"]);
            })
            ->append(['proxy_name', 'city_name'])
            ->order(['create_time' => 'desc'])
            ->paginate($params);
    }

    public function add($data)
    {
        $data['app_id'] = self::$app_id;
        $data["province_id"] = $data["region_id"][0];
        $data["city_id"] = $data["region_id"][1] ?? 0;
        $data["is_audit"] = 0;
        return self::create($data);
    }

    /**
     * 修改
     */
    public function edit($data, $proxy_id)
    {
        // 开启事务
        $this->startTrans();
        try {
            $data['app_id'] = self::$app_id;
            $data["province_id"] = $data["region_id"][0];
            $data["city_id"] = $data["region_id"][1] ?? 0;
            $data["is_audit"] = 0;
            $data["publish_status"] = 0;
            if ($this['proxy_id'] !== $proxy_id) {
                $this->error = '您无权编辑此记录';
                return false;
            }
            $this->save($data);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }


}